<?php
declare (strict_types=1);

namespace app\admin\controller\wechat;

use app\common\controller\BaseController;
use app\admin\model\wechat\Account as AccountModel;
use app\admin\model\wechat\Auth as AuthModel;

use app\common\library\wechat\Crawler;
use think\exception\ValidateException;

class Account extends BaseController
{

    protected $noNeedRight = ['getAccountList'];

    /**
     * @var AccountModel
     */
    protected $model;

    protected $modelValidate = true;

    public function initialize()
    {
        parent::initialize();

        $this->model = new AccountModel;
    }

    /**
     * 查看
     * @param int $id
     */
    public function read($id = NULL)
    {
        $fakeid = $this->request->param('fakeid', '', 'trim');
        if ($fakeid) {
            $row = $this->model->where('fakeid', '=', $fakeid)->find();
        } else {
            $row = $this->model->find($id);
        }
        if (!$row) {
            return $this->error('未查询到任何记录');
        }
        $result = array('row' => $row);

        return $this->success('请求成功', $result);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                //模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    try {
                        $this->validate($params, $validate);
                        $validateRes = true;
                    } catch (ValidateException $e) {
                        // 验证失败 输出错误信息
                        $validateRes = $e->getError();
                    }
                    if ($validateRes !== true) {
                        return $this->error($validateRes);
                    }
                }
                $accountInfo = $this->accountInfo($params['nickname']);
                if ($accountInfo == false) {
                    return $this->error('系统错误，请稍后重试');
                }
                $qrcode = '';
                if (!empty($accountInfo['alias'])) {
                    $qrcode = 'https://open.weixin.qq.com/qr/code?username=' . $accountInfo['alias'];
                }

                $account = [
                    'nickname' => $accountInfo['nickname'],
                    'signature' => $accountInfo['signature'],
                    'round_head_img' => $accountInfo['round_head_img'],
                    'alias' => $accountInfo['alias'],
                    'fakeid' => $accountInfo['fakeid'],
                    'service_type' => $accountInfo['service_type'],
                    'qrcode' => $qrcode,
                ];
                $params = array_merge($params, $account);
                $result = $this->model->save($params);
                if ($result !== false) {
                    //微信采集队列-历史
                    $queueData = [
                        'type' => 'history',
                        'alias' => $account['alias'],
                        'fakeid' => $account['fakeid'],
                        'begin' => 0,
                        'finish' => 50,
                        'query' => '',
                    ];
                    add_wechat_queue($queueData, 3);

                    //微信采集队列-最新
                    $queueData = [
                        'type' => 'latest',
                        'alias' => $account['alias'],
                        'fakeid' => $account['fakeid'],
                        'source' => 'queue'
                    ];
                    $delay = mt_rand(3000, 4200);
                    add_wechat_queue($queueData, $delay);

                    return $this->success('添加成功');
                } else {
                    return $this->error(lang('No rows were inserted'));
                }
            }
            return $this->error(lang('Parameter %s can not be empty', ''));
        }
    }

    public function getAccountList()
    {
        $nickname = $this->request->param('keyword', '', 'trim');
        if (empty($nickname)) {
            //$this->error('请输入公众号名称');
            $result = [];
        } else {
            $crawler = new Crawler();
            $list = $crawler->getAccountListByCommon($nickname);
            if ($list !== false) {
                foreach ($list as $item) {
                    $result[] = [
                        'label' => $item['nickname'],
                        //'value' => $item['alias'],
                        'value' => $item['appid'],
                        'appid' => $item['appid'],
                        'head_img' => $item['headimg_url'],
                    ];
                }
            } else {
                $result = [];
            }
        }

        return $this->success('请求成功', $result);
    }

    protected function accountInfo($nickname)
    {
        list($token, $cookie) = AuthModel::getAuthInfo();

        $crawler = new Crawler();

        $crawler->setToken($token);
        $crawler->setCookie($cookie);

        $list = $crawler->getAccountListBySelf($nickname);
        if ($list !== false) {
            foreach ($list as $item) {
                if ($item['nickname'] == $nickname) {
                    $account = $item;
                    break;
                }
            }
        } else {
            if ($crawler->getErrorCode() == '200003') {
                AuthModel::updateAuth($token);
            }
            $account = false;
        }
        return $account;
    }
}